package plugins.detail;

import kd.bos.base.BaseShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.ShowType;
import kd.bos.form.control.Button;
import kd.bos.form.control.Control;
import kd.bos.form.control.Image;
import kd.bos.form.control.Label;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.url.UrlService;


import java.util.*;

public class ShowDishes extends AbstractFormPlugin {
    // 缓存Key定义
    private static final String DISH_IDS_CACHE_KEY = "randomDishIds";

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        loadRandomDishes();
    }

    private void loadRandomDishes() {
        // 1. 从数据库加载所有菜品
        String entityName = "dcb4_dishes";
        String selectFields = "dcb4_picture,name,id";
        DynamicObject[] allDishes = BusinessDataServiceHelper.load(
                entityName, selectFields, new QFilter[0], "", Integer.MAX_VALUE
        );

        if (allDishes == null || allDishes.length == 0) return;

        // 2. 随机选择4道菜品
        List<DynamicObject> dishList = Arrays.asList(allDishes);
        Collections.shuffle(dishList);
        List<DynamicObject> selectedDishes = dishList.subList(0, Math.min(4, dishList.size()));

        // 3. 存储ID到页面缓存

        // 清空之前的缓存
        this.getView().getPageCache().remove(DISH_IDS_CACHE_KEY);

        List<String> dishIds = new ArrayList<>();
        for (int i = 0; i < selectedDishes.size(); i++) {
            DynamicObject dish = selectedDishes.get(i);
            dishIds.add(dish.getString("id"));
            updateDishUI(i, dish);
        }
        this.getView().getPageCache().put(DISH_IDS_CACHE_KEY, String.join(",", dishIds));
    }

    private void updateDishUI(int index, DynamicObject dish) {
        // 更新图片控件
        Image image = (Image) this.getView().getControl("dcb4_imageap1" + (index + 1));
        if (image != null) {
            String imageUrl = UrlService.getImageFullUrl(dish.getString("dcb4_picture"));
            image.setUrl(imageUrl);
        }

        // 更新标签控件
        Label label = (Label) this.getView().getControl("dcb4_labelap2" + (index + 1));
        if (label != null) {
            label.setText(dish.getString("name"));
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        // 为4组控件注册点击监听
        for (int i = 1; i <= 4; i++) {
            registerControlListeners(i);
        }

        // 为按钮注册点击监听
        Button button = (Button) this.getView().getControl("dcb4_refresh");
        if (button != null) {
            button.addClickListener(this);
        }
    }

    private void registerControlListeners(int index) {
        // 正确添加点击监听器
        addImageClickListener("dcb4_imageap1" + index);
        addLabelClickListener("dcb4_labelap2" + index);
    }

    private void addImageClickListener(String controlKey) {
        Image image = (Image) this.getView().getControl(controlKey);
        if (image != null) {
            image.addClickListener(this);
        }
    }

    private void addLabelClickListener(String controlKey) {
        Label label = (Label) this.getView().getControl(controlKey);
        if (label != null) {
            label.addClickListener(this);
        }
    }

    @Override
    public void click(EventObject evt) {
        Control source = (Control) evt.getSource();
        String controlKey = source.getKey();

        // 检查是否点击了刷新按钮
        if ("dcb4_refresh".equals(controlKey)) {
            loadRandomDishes();
            return; // 处理完刷新逻辑后退出方法
        }

        // 1. 从缓存获取菜品ID列表
        String dishIdsStr = (String) this.getView().getPageCache().get(DISH_IDS_CACHE_KEY);
        if (dishIdsStr == null) return;

        List<String> dishIds = Arrays.asList(dishIdsStr.split(","));
        int dishIndex = getDishIndexFromControl(controlKey);

        // 2. 打开对应菜品详情
        if (dishIndex >= 0 && dishIndex < dishIds.size()) {
            openDishForm(dishIds.get(dishIndex));
        }
    }

    private int getDishIndexFromControl(String controlKey) {
        // 从控件key提取索引 (dcb4_imageap11 -> 0, dcb4_imageap12 -> 1)
        int index = Integer.parseInt(controlKey.substring(12));

        return index-11; // 转换为0-based索引
    }

    private void openDishForm(String dishId) {
        BaseShowParameter parameter = new BaseShowParameter();
        parameter.setFormId("dcb4_dishes");  // 菜品表单标识
        parameter.setPkId(dishId);
        parameter.getOpenStyle().setShowType(ShowType.Modal);
        this.getView().showForm(parameter);
    }
}
